<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="findRoleByName"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="treeData"
          :props="defaultProps"
          :expand-on-click-node="false"
          default-expand-all
          highlight-current
          @current-change="selectNode"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            v-permission="'add-employee'"
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
          >添加员工</el-button>

          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>

          <el-button size="mini" @click="downLoadFile">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
          <el-table-column type="selection" width="50" />
          <!-- 头像 -->
          <el-table-column prop="staffPhoto" label="头像" width="80">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <div v-else class="username">
                {{ row.username.charAt(0) }}
              </div>
            </template></el-table-column>
          <el-table-column prop="username" label="姓名" width="width" />
          <!-- 手机号 -->
          <el-table-column sortable prop="mobile" label="手机号" width="width" />
          <!-- 工号 -->
          <el-table-column sortable prop="workNumber" label="工号" width="width" />
          <!-- 聘用形式 -->
          <el-table-column prop="formOfEmployment" label="聘用形式" width="width">
            <template #default="obj">
              {{ obj.row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <!-- 部门 -->
          <el-table-column prop="departmentName" label="部门" width="width" />
          <!-- 入职时间 -->
          <el-table-column sortable prop="timeOfEntry" label="入职时间" width="width" />
          <!-- 操作 -->
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="obj">
              <template v-if="!obj.row.isEdit">
                <!-- 查看 -->
                <el-button
                  v-permission="'show'"
                  type="text"
                  size="small"
                  @click="$router.push(`/employee/detail/${obj.row.id}`)"
                >查看</el-button>
                <!-- 角色 -->
                <el-button
                  v-permission="'employee'"
                  type="text"
                  size="small"
                  @click="btnRoles(obj.row.id)"
                >角色</el-button>
                <!-- 删除 -->
                <el-button v-permission="'del'" type="text" size="small" @click="delDialog = true">
                  <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="deleteRole(obj.row.id)">
                    <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
                  </el-popconfirm>
                </el-button>
              </template>
              <template v-else>
                <el-button type="primary" @click="editRole(obj.row)">确定</el-button>
                <el-button type="primary" @click="obj.row.isEdit = false">取消</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="params.pageSize"
          :current-page="params.page"
          @current-change="pageChange"
        />

      </div>

    </div>

    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>

      </el-checkbox-group>

      <el-row :style="{padding:'10px'}" type="flex" justify="center">
        <el-button size="mini" type="primary" @click="onAssignRole">确定</el-button>
        <el-button size="mini" type="primary" @click="showRoleDialog = false">取消</el-button>
      </el-row>

    </el-dialog>

    <ImportExcel :show-excel-dialog.sync="showExcelDialog" />

  </div>

</template>

<script>
import { getDepartmentsAPI } from '@/api/department'
import { getEmployeeList, downLoadFileAPI, delEmployeeAPI,
  getEnableRoleListAPI, getEmployeeDetailAPI, assignRoleAPI } from '@/api/employee'
import { buildTree } from '@/utils'
import { saveAs } from 'file-saver'
import ImportExcel from './import-excel.vue'
import { Message } from 'element-ui'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      treeData: [],
      tableData: [],
      // 存储查询参数
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      params: {
        page: 1,
        pagesize: 10,
        departmentId: null
      },
      total: 0,
      keyword: null,
      showExcelDialog: false,
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: []// 用来双向绑定数据的
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    // 获取部门数据
    async getTreeData() {
      const res = await getDepartmentsAPI()
      const tree = buildTree(res)
      this.treeData = tree
      this.params.departmentId = tree[0].id
      this.getEmployeeList()
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.params.departmentId)
      })
    },
    // 获取员工列表
    async getEmployeeList() {
      const result = await getEmployeeList({ ...this.params, keyword: this.keyword })
      this.tableData = result.rows
      this.total = result.total
      console.log('total --->', result.total)
    },
    // tree的节点变化，获取节点的id，并获取员工列表
    selectNode(node) {
      this.params.departmentId = node.id
      this.getEmployeeList()
    },
    // 页码改变
    pageChange(page) {
      this.params.page = page
      this.getEmployeeList()
    },
    // 名字模糊搜索
    findRoleByName() {
      // 防抖
      clearTimeout(this.timerId)
      this.timerId = setTimeout(() => {
        this.params.page = 1
        this.getEmployeeList()
      }, 500)
    },
    // 下载模板文件
    async downLoadFile() {
      // 下载文件
      // 1. 发送请求，获取文件的二进制数据
      const blob = await downLoadFileAPI()
      // 2. 把二进制数据保存为文件'
      saveAs(blob, '员工列表.xlsx')
    },
    // 删除员工
    async deleteRole(id) {
      await delEmployeeAPI(id)
      if (this.tableData.length === 1 && this.params.page > 1) {
        this.params.page--
      }
      this.getEmployeeList()
      Message.success('删除成功')
    },
    // 角色列表
    async btnRoles(id) {
      this.roleList = await getEnableRoleListAPI()
      const { roleIds } = await getEmployeeDetailAPI(id)
      this.showRoleDialog = true
      this.roleIds = roleIds
      this.currentId = id
    },
    // 给员工分配角色
    async onAssignRole() {
      await assignRoleAPI({ id: this.currentId, roleIds: this.roleIds })
      Message.success('分配成功')
      this.showRoleDialog = false
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
